<template>
	<view class="imgUpload">
		<view v-if="choose" @click="img" class="add"></view>
		<view v-else v-for="(item,index) in imglist" :key="index" class="conent">
			<image @error="error" class="img" :src="item"></image>
			<view class="close" @click="remove(index)"></view>
		</view>
	</view>
</template>

<script>
	import { config } from '../util/http'
	import { getToken } from '../util/auth.js'
	export default {
		name:'img',
		props:['image'],
		data() {
			return {
				choose: true,
				imglist:[]
			};
		},
		watch: {
		   'image': function (v) {
			  console.log(v)
			  this.imglist = [v]
			  this.choose = false
		   }
		  },
		methods:{
			remove(index){
				this.imglist.splice(index,1);
				this.choose = true
			},
			error(e){
				console.log(e.detail)
				uni.showToast({
					title:'图片地址错误'
				})
			},
			img(){
				uni.chooseImage({
				    success: (chooseImageRes) => {
				        const tempFilePaths = chooseImageRes.tempFilePaths;
						this.imglist = tempFilePaths;
						console.log(tempFilePaths)
						this.choose = false
				        uni.uploadFile({
				            url: `${config.baseUrl}imagesAll/upload`, //仅为示例，非真实的接口地址
				            filePath: tempFilePaths[0],
				            name: 'file',
							header:{
								'Authorization': getToken() 
							},
				            success: (uploadFileRes) => {
								this.$emit('unload',JSON.parse(uploadFileRes.data))
				            },
							fail:()=>{
								this.$emit('unload',JSON.parse(uploadFileRes))
							}
				        });
				    }
				});
			}
		}
	}
</script>

<style lang="scss">
.imgUpload{
	position: relative;
	width:65px;
	height:65px;
	margin: 10px;
	background:rgba(242,242,245,1);
	border-radius:5px;
	.add{
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%,-50%);
		width:30px;
		height:30px;
		background-size: 130% 130%;
		background-position: center center;
		background-image: url();
	}
	.conent{
		position: relative;
		width: 100%;
		height: 100%;
		.img{
			width: 100%;
			height: 100%;
		}
	}
	.close{
		width: 20px;
		height: 20px;
		background-image: url();
		background-position: center center;
		background-size: 100% 100%;
		position: absolute;
		border-radius: 50%;
		border: 1px solid #ccc;
		top: -5px;
		right: -5px;
	}
}
</style>
